package actions.leetcode.dialog;

import utils.CommonUtil;
import utils.WidgetUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class LeetCodeConfigDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JFormattedTextField inputNum;
    private JFormattedTextField inputUrl;
    private JFormattedTextField inputName;
    private ICallBack mCallBack;

    public static void runWithCallBack(ICallBack callBack) {
        LeetCodeConfigDialog dialog = new LeetCodeConfigDialog();
        dialog.mCallBack = callBack;
        CommonUtil.showDialog(dialog, "生成LeetCode模板");
    }

    public LeetCodeConfigDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(e -> onOK());
        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)
                , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        // add your code here
        if (WidgetUtil.checkTextFieldNotEmpty(inputNum, "请正确输入问题编号！")
                && WidgetUtil.checkTextFieldNotEmpty(inputName, "请正确输入问题名！")
                && WidgetUtil.checkTextFieldNotEmpty(inputUrl, "请正确输入问题链接！")) {
            if (mCallBack != null) {
                mCallBack.onInputConfirm(inputNum.getText(), inputUrl.getText(), inputName.getText());
            }

            dispose();
        }
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    public interface ICallBack {
        void onInputConfirm(String number, String url, String name);
    }

    public static void main(String[] args) {
        runWithCallBack(null);
    }
}
